package com.yangle.frame.common.utils;


import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by yangle on 2018/6/5.
 */
@Component
public class EhcacheUtils {
    private Logger logger= LoggerFactory.getLogger(EhcacheUtils.class);
    @Autowired
    private  CacheManager cacheManager;

    public  void update(String key, Object object){

        Cache cache = cacheManager.getCache("yangle");
        if(cache.get(key)!=null && !cache.get(key).equals("")){
            cache.remove(key);
        }
        Element element = new Element(key,object);
        cache.put(element);
        logger.info("update a key :"+key+";value:"+object);
    }
    public  void del(String key){
        logger.info("del a key :"+key);
        Cache cache = cacheManager.getCache("yangle");
        if(cache.get(key)!=null && !cache.get(key).equals("")){
            cache.remove(key);
        }
    }
    public  Object get(String key){
        Object object = null;
        Cache cache = cacheManager.getCache("yangle");

        if(cache.get(key)!=null && !cache.get(key).equals("")){
            object = cache.get(key).getObjectValue();
        }
        logger.info("get a key :"+key+";value:"+object);
        return object;
    }


    public  void clear(){
        logger.info("clear all caches");
        Cache cache = cacheManager.getCache("yangle");
        cache.removeAll();
    }
}
